#include <my_head.h>

typedef struct _Msg{
    int len;
    char buff[128];
}msg_t;

int main(int argc, const char *argv[]){
    if(3 != argc){
        printf("Usage : %s <IP> <PORT>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd)
        ERR_LOG("socket error");
    
    // 填充 服务器! 网络信息结构体
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t serveraddr_len = sizeof(serveraddr);

    // 与服务器建立连接
    if(-1 == connect(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len))
        ERR_LOG("connect error");
    printf("与服务器连接成功...\n");

    int nbytes = 0;
    char buff[128] = {0};
    char file_name[32] = {0};
    // 给服务器发送要下载的文件名
RE_NAME:
    printf("请输入要下载的文件名:");
    fgets(file_name, sizeof(file_name), stdin);
    file_name[strlen(file_name)-1] = '\0'; // 清理 '\n'
    if(-1 == send(sockfd, file_name, sizeof(file_name), 0)){
        ERR_LOG("send error");
    }
    // 等服务器回复 文件是否存在
    if(-1 == recv(sockfd, buff, sizeof(buff), 0)){
        ERR_LOG("send error");
    }
    if(!strcmp(buff, "FILE NOT EXIST")){
        printf("文件 [%s] 不存在\n", file_name);
        goto RE_NAME;
    }
    // 执行到此 说明文件存在
    int fd = 0;
    if(-1 == (fd = open(file_name, O_WRONLY|O_CREAT|O_TRUNC, 0664)))
        ERR_LOG("open error");
#if 0
    // 循环接收文件内容 并写入本地文件中
    while(1){
        memset(buff, 0, sizeof(buff));
        if(-1 == (nbytes = recv(sockfd, buff, sizeof(buff), 0))){
            ERR_LOG("send error");
        }
        if(!strcmp(buff, "****OVER****")){
            break;
        }
        if(-1 == write(fd, buff, nbytes))
            ERR_LOG("write error");
    }
#else
    msg_t msg;
    // 循环接收文件内容 并写入本地文件中
    while(1){
        if(-1 == (nbytes = recv(sockfd, &msg, sizeof(msg), 0))){
            ERR_LOG("send error");
        }
        if(0 == msg.len){
            break;
        }
        if(-1 == write(fd, msg.buff, msg.len))
            ERR_LOG("write error");
    }

#endif
    close(fd);
    printf("文件 [%s] 下载成功\n", file_name);
    // 关闭套接字
    close(sockfd);

    return 0;
}